<template>
  <BasicModal
    v-bind="$attrs"
    @register="register"
    :title="titleMap[modalInfo.type]"
    :width="436"
    :minHeight="150"
    :zIndex="1008"
    centered
    @ok="confirmSubmit"
    @cancel="resetModal"
  >
    <div class="modify-info">
      <div class="info-box">
        <a-form
          hideRequiredMark
          :colon="false"
          ref="formRef"
          autocomplete="off"
          :label-col="{ style: { width: ['phone', 'bindPhone'].includes(modalInfo.type) ? '90px' : '70px' } }"
          style="width: 100%"
          :model="formState"
          :rules="getFormRules"
          @keypress.enter="confirmSubmit"
        >
          <a-form-item label="姓名" name="userName" v-if="modalInfo.type === 'userName'">
            <a-input allowClear placeholder="请输入姓名" v-model:value.trim="formState.userName"> </a-input>
          </a-form-item>
          <template v-if="modalInfo.type === 'phone' || modalInfo.type === 'bindPhone'">
            <a-form-item label="原手机号码" v-if="modalInfo.type === 'phone'">
              <div class="form-txt">
                {{ modalInfo.userInfo.phoneNumber }}
              </div>
            </a-form-item>
            <a-form-item label="新手机号码" name="newPhone">
              <a-input
                allowClear
                :maxlength="11"
                placeholder="请输入新手机号码"
                v-model:value.trim="formState.newPhone"
              >
              </a-input>
            </a-form-item>
            <a-form-item label="手机验证码" name="smsCode" class="sms-code">
              <CountDownInput
                allowClear
                :maxlength="6"
                customClass="light-code small-btn"
                v-model:value="formState.smsCode"
                placeholder="请输入验证码"
                :sendCodeApi="sendCodeApi"
              />
            </a-form-item>
          </template>
          <a-form-item label="邮箱" name="email" v-if="modalInfo.type === 'bindEmail'">
            <a-input allowClear placeholder="请输入邮箱" v-model:value.trim="formState.email"> </a-input>
          </a-form-item>
          <template v-if="modalInfo.type === 'email'">
            <a-form-item label="原邮箱">
              <div class="form-txt">
                {{ modalInfo.userInfo.email }}
              </div>
            </a-form-item>
            <a-form-item label="新邮箱" name="newEmail">
              <a-input allowClear placeholder="请输入新邮箱" v-model:value.trim="formState.newEmail"> </a-input>
            </a-form-item>
          </template>
        </a-form>
      </div>
    </div>
  </BasicModal>
</template>
<script lang="ts" setup name="modifyPwd">
import { ref, reactive, unref } from 'vue'
import { BasicModal, useModalInner } from '@/components/Modal'
import CountDownInput from '@/components/CountDown/CountDownInput.vue'
import { userStore } from '@/store/modules/user'
import { cloneDeep } from 'lodash-es'
import { message } from 'ant-design-vue'
import { pattern } from '@/utils/validate/index'
import type { Rule } from 'ant-design-vue/es/form'
import api from '@/api'

const { updateEmail, getCode, updatePhone } = api

const emit = defineEmits(['operateSuccess', 'register'])

const userModule = userStore()

const titleMap: any = {
  userName: '修改姓名',
  phone: '修改手机号',
  email: '修改邮箱',
  bindEmail: '绑定邮箱',
  bindPhone: '绑定手机号'
}
const modalInfo = reactive<any>({
  type: '',
  userInfo: {}
})

const formRef = ref()
const formState = reactive({
  userName: '',
  newPhone: '',
  smsCode: '',
  email: '',
  newEmail: ''
})
// 规则校验
const validatePhone = async (rule: Rule, value: string) => {
  if (!value) {
    return Promise.reject('请输入新手机号码')
  } else if (!pattern.regexp_cell_phone.test(value)) {
    return Promise.reject('请输入正确的手机号码')
  } else if (value === modalInfo.userInfo.phone) {
    return Promise.reject('新手机号码不能与原手机号码一致')
  } else {
    return Promise.resolve()
  }
}
const validateEmail = async (rule: Rule, value: string) => {
  if (!value) {
    return Promise.reject('请输入邮箱')
  } else if (!pattern.regexp_email.test(value)) {
    return Promise.reject('请输入正确的邮箱')
  } else if (value === modalInfo.userInfo.email) {
    return Promise.reject('新邮箱不能与原邮箱一致')
  } else {
    return Promise.resolve()
  }
}
const getFormRules = {
  userName: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  newPhone: [{ required: true, validator: validatePhone, trigger: 'blur' }],
  smsCode: [{ required: true, message: '请输入验证码', trigger: 'blur' }],
  email: [
    {
      required: true,
      message: '请输入邮箱',
      trigger: 'blur'
    },
    {
      pattern: pattern.regexp_email,
      message: '请输入正确的邮箱',
      trigger: 'blur'
    }
  ],
  newEmail: [{ required: true, validator: validateEmail, trigger: 'blur' }]
}

const [register, { setModalProps, changeOkLoading, closeModal }] = useModalInner((data) => {
  let dataObj = cloneDeep(data)
  modalInfo.type = dataObj.type
  modalInfo.userInfo = dataObj.userInfo
  if (dataObj.type === 'userName') {
    formState.userName = dataObj.userInfo?.userName
  }
})

// 发送短信验证码
const sendCodeApi = async () => {
  try {
    await unref(formRef).validate(['newPhone'])
    await getCode({ phone: formState.newPhone, busType: 3 })
    message.success('手机验证码已发送，请查收')
    return true
  } catch (error) {
    return false
  }
}

const getDelContainer = () => {
  return document.querySelector('.page-wrapper')
}

const resetModal = () => {
  changeOkLoading(false)
  unref(formRef).resetFields()
}
const confirmSubmit = async () => {
  try {
    await unref(formRef).validate()
    changeOkLoading(true)
    if (modalInfo.type === 'userName') {
      // await userCurrentUpdate({
      //   userName: formState.userName
      // })
    } else if (modalInfo.type === 'email' || modalInfo.type === 'bindEmail') {
      await updateEmail({
        email: modalInfo.type === 'email' ? formState.newEmail : formState.email
      })
    } else if (modalInfo.type === 'phone' || modalInfo.type === 'bindPhone') {
      await updatePhone({
        phone: formState.newPhone,
        smsCode: formState.smsCode
      })
    }

    closeModal()
    changeOkLoading(false)
    resetModal()
    message.success('信息修改成功')
    emit('operateSuccess')
  } catch (error) {
    changeOkLoading(false)
  }
}
</script>
<style lang="less" scoped>
.modify-info {
  padding: 10px 30px 0;
  .info-box {
    min-height: 150px;
    display: flex;
    align-items: center;
  }
}
</style>
